/*
 * BluetoothServer.java
 *
 * Created on April 18, 2007, 12:45 AM
 *
 */
package awareness.communication;

import awareness.AwarenessMidlet;
import java.io.DataOutputStream;

import java.io.IOException;
import java.io.OutputStream;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import javax.microedition.midlet.MIDlet;

public class StatisticsServer implements Runnable {

//    private boolean listening = true;
    private AwarenessMidlet midlet;
    private L2CAPConnection con;
    private String message_to_send;
    private String my_name;

    /** Creates a new instance of BluetoothServer */
    public StatisticsServer(AwarenessMidlet midlet, String msg) {
        this.midlet = midlet;
        message_to_send = msg;
        Thread t = new Thread(this);
        t.start();
    }

    public void run() {
        while (true) {
            try {
                LocalDevice local_device = LocalDevice.getLocalDevice();
                local_device.setDiscoverable(DiscoveryAgent.GIAC);
                my_name = local_device.getFriendlyName();
            } catch (Exception e) {
            }
            try {
                String service_UUID = "00000000000010008000006057028A06";
                String url = "btl2cap://localhost:" + service_UUID + ";name=" + my_name;
                L2CAPConnectionNotifier notifier = (L2CAPConnectionNotifier) Connector.open(url);
                L2CAPConnection con = notifier.acceptAndOpen();
                byte[] b = message_to_send.getBytes();
                try {
                    con.send(b);
                } catch (IOException e) {
                    System.out.println(e);
                }
                con.close();
                notifier.close();
            } catch (BluetoothStateException e) {
                break;
            } catch (IOException f) {
                break;
            }
        }
    }


    private void send(String s) {
        byte[] b = s.getBytes();
        try {
            con.send(b);
        } catch (IOException e) {
            System.out.println(e);
        }
    }

    private String getName() {
        return my_name;
    }
}
